<?php

namespace App\Transformers;

use App\Models\Task;
use App\Models\User;
use League\Fractal\TransformerAbstract;

class TaskTransformer extends TransformerAbstract
{


    protected $availableIncludes = ['createUser','carryUser'];

    public function transform(Task $task)
    {
        //没打通电话人数
        $not_call_count = $task->fsUserTask->where('status',0)->count();
        //打通电话人数
        $call_count = $task->fsUserTask->where('status',1)->count();
        //任务会员人数
        $count = $task->count;
        //完成度 打通电话人数/会员人数
        $comple_task_rate = round( $call_count / $count, 2);
        //接通分组后的人数
        $comple_people_count = $task->phoneRecord->where('call_status','completed')->groupBy('fs_user_id')->count();
        //接通率
        $comple_people_rate = round( $comple_people_count / $count, 2);
        return [
            'id' => $task->id,
            'name' => $task->name,
            'carry_user_id' => $task->carry_user_id,
            'create_user_id' =>  $task->create_user_id,
            'start_time' => $task->start_time,
            'end_time' => $task->end_time,
            'status' => $task->status,
            'count' => $count, //任务会员人数
            'not_call_count' => $not_call_count, //没打通的人数
            'comple_call_count' => $call_count, //打通人数
            'comple_task_rate' =>$comple_task_rate, //任务完成率
            'comple_people_count' => $comple_people_count,
            'comple_people_rate' =>$comple_people_rate,
            'created_at' => empty($task->created_at)?'':$task->created_at->toDateTimeString(),
            'updated_at' => empty($task->updated_at)?'':$task->updated_at->toDateTimeString(),
        ];
    }

    public function includeCreateUser(Task $task)
    {
        return $this->nullOrItem($task->createUser, new UserTransformer());
    }
    public function includeCarryUser(Task $task)
    {
        return $this->nullOrItem($task->carryUser, new UserTransformer());
    }
    public function nullOrItem($data, $transformer, $resourceKey = null)
    {
        if (is_null($data)) {
            return parent::null();
        } else {
            return parent::item($data, $transformer, $resourceKey);
        }
    }
}